<template>
  <view class="user-page">
    <view v-if="isLogin.value && tenant?.option.length" class="tenant-popup">
      <wd-drop-menu>
        <wd-drop-menu-item
          :title="truncatedText"
          icon="caret-down-small"
          icon-size="40px"
          v-model="tenant.value"
          :options="tenant.option"
          @change="handleChangeTenant"
        />
      </wd-drop-menu>
    </view>
    <view v-else class="tenant-popup">家装通</view>
    <view class="header" @click="handleView">
      <image :src="userInfo?.avatarUrl"></image>
      <view class="header-con">
        <text v-if="userInfo?.nickName" class="header-con-name">{{
          userInfo?.nickName
        }}</text>
        <view v-if="isLogin.value" class="header-con-location">
          <image
            class="location-icon"
            src="http://51-jzt-dev.oss-cn-hangzhou.aliyuncs.com/miniapp/location.png"
          ></image>
          {{ userInfo?.residence }}
        </view>
      </view>
      <view class="header__phone" @click.stop="handlePhone" style="opacity: 0">
       <image  class="header__phone__img" src="http://51-jzt-dev.oss-cn-hangzhou.aliyuncs.com/miniapp/contact-phone.png" />
          电话咨询
      </view>
    </view>
    <ViewTabs />
   <view
     v-if="loginErr || (!is500 && !isLogin.value)"
     class="bg-panel no-login"
   >
     <view class="bg-panel-tip">请先授权，系统会自动匹配为您服务的企业！</view>
   </view>
    <view v-if="is500 && noScanCode" class="bg-panel no-business">
      <view class="bg-panel-tip">未找到商家！请联系商家提供专属小程序码！</view>
    </view>
    <view
      v-if="(is500 && noPhoneNumber) || (isLogin.value && !userInfo.customerId)"
      class="bg-panel no-phone"
    >
      <view class="bg-panel-tip"
        >该手机号暂未匹配到相关“合同”请联系企业设计师！</view
      >
    </view>

    <!-- 登录提示 -->
    <wd-overlay
      :show="isLogin.popShow"
      @click="isLogin.popShow = false"
      :zIndex="99"
    >
      <view class="wrapper">
        <view class="tip">温馨提示</view>
        <view class="info">请先授权登录</view>
        <view class="btn-group">
          <button>取消</button>
          <text class="line" />
          <button
            open-type="getPhoneNumber"
            @getphonenumber="getPhoneNumber"
            class="confirm"
          >
            确认
          </button>
        </view>
      </view>
    </wd-overlay>
   <template v-if="isLogin.value && userInfo.customerId">
      <importantMsg />
      <circleTitle
        title="项目进度"
        more-title="查看验收"
        @more="viewAcceptance"
      />
      <Progress v-if="progressList?.length" :data="progressList"></Progress>
      <Empty v-else bgColor="#ffffff" />
      <circleTitle
        title="施工日志"
        more-title="查看更多"
        @more="viewconstruction"
      />
      <view>
        <ConstructionItem
          v-for="item in logList"
          :item="item"
          :key="item"
        ></ConstructionItem>
        <Empty v-if="!logList?.length" bgColor="#ffffff" />
      </view>
   </template>
    <TabBar :list="tabList" :defaultTab="1" @handelTabBar="handelTabBar">
    </TabBar>
    <!-- start phonePopup-->
    <phone-popup v-if="showPhonePopup" v-model="showPhonePopup"></phone-popup>
    <!-- end phonePopup-->
  </view>
</template>
<script setup>
import { ref, computed, onMounted, onUnmounted, watch, nextTick } from "vue";
import TabBar from "@/components/tabBar/index.vue";
import ViewTabs from "./components/viewTab/viewTab.vue";
import importantMsg from "./components/importantMsg/importantMsg.vue";
import { onHide, onPullDownRefresh } from "@dcloudio/uni-app";
import useTabBarStore from "@/store/modules/base/tabBar";
import useUserStore from "@/store/modules/user/index.js";
import { useTokenStore } from "@/store/modules/token/index.js";
import Progress from "./components/progress/index.vue";
import circleTitle from "@/components/circle-title/index.vue";
import ConstructionItem from "@/components/constructionItem/index.vue";
import { getList } from "@/api/construction";
import { getProgressList } from "@/api/user.js";
import Empty from "@/components/empty/index.vue";
import { getToken } from "@/api/user";import phonePopup from "./components/phonePopup.vue"
const store = useTabBarStore();
const userStore = useUserStore();
const tokenStore = useTokenStore();
const progressList = ref();
const logList = ref([]);
const is500 = ref(false);
const loginErr = ref(false);
const noScanCode = ref(0);
const noPhoneNumber = ref(0);
const {
  tenant,
  userInfo,
  isLogin,
  updateToken,
  getTenantList,
  getMessageList,
  setData,
} = userStore;
watch(userInfo, (newVal) => {
  nextTick(() => {
    Object.assign(userInfo, newVal);
  });
});
const handleView = () => {
  if (!isLogin.value) {
    isLogin.popShow = true;
  }
};
const getPhoneNumber = async (e) => {
  resetStatus();
  if (e.detail.errMsg === "getPhoneNumber:ok") {
    // 用户同意授权，获取手机号信息
    const { code } = e?.detail;
    try {
      const { data } = await getToken({
        tenantId: uni.getStorageSync("tenantId"),
        code,
      });
      setData(data);
      uni.removeStorageSync("isScan");
      setTimeout(() => {
        getLogProgressList();
      }, 500);
    } catch (error) {
      console.log("catch>>>>", error);
      is500.value = true;
      if (error?.data?.code === 530) {
        // 未找到商家 联系设计师获取小程序码
        noScanCode.value = 1;
      } else if (error?.data?.code === 535) {
        // 手机号未匹配到合同
        noPhoneNumber.value = 1;
      } else {
        loginErr.value = true;
        // isLogin.popShow = true;
      }
    }
  } else {
    console.error("用户拒绝授权", e.detail.errMsg);
  }
};
const resetStatus = () => {
  is500.value = false;
  loginErr.value = false;
  noScanCode.value = 0;
  noPhoneNumber.value = 0;
};
onHide(() => {
  resetStatus();
});
onMounted(() => {
  tokenStore.syncToken();
  const token = tokenStore.getCookie("token");
  const isScan = uni.getStorageSync("isScan");
  if (token) {
    const cachedUser = uni.getStorageSync("userInfo");
    if (cachedUser) {
      Object.assign(userInfo, cachedUser);
    }
    if (!isScan) {
      // 直接通过最近进入，非扫码，已登录，不调任何接口
      getMessageList();
      getTenantList();
      getLogProgressList();
    }
  }
});
// 处理下拉刷新
onPullDownRefresh(() => {
  getMessageList();
  getTenantList();
  getLogProgressList();
  setTimeout(() => {
    uni.stopPullDownRefresh(); // 停止下拉刷新
  }, 1000);
});

// 获取租户列表
const truncatedText = computed(() => {
  if (tenant?.currentTenant) {
    return tenant.currentTenant.length > 7
      ? tenant.currentTenant.substring(0, 7) + "..."
      : tenant.currentTenant;
  }
});
const getTenantCheckToken = async () => {
  try {
    const res = await updateToken();
    setData(res?.data);
    setTimeout(() => {
      getLogProgressList();
    }, 500);
  } catch (error) {
    console.log(error);
  }
};
function handleChangeTenant({ value }) {
  try {
    uni.setStorageSync("tenantId", value);
    tenant.value = value;
    tenant.currentTenant =
      tenant.option.find((item) => item.value === value)?.label || null;
    getTenantCheckToken();
  } catch (error) {
    console.error("切换租户失败", error);
  }
}

// 租户列表 end

const tabList = store.list;
const handelTabBar = (index) => {
  if (!isLogin.value) {
    isLogin.popShow = true;
  } else {
    uni.redirectTo({
      url: tabList[index].pagePath,
    });
  }
};
/**
 * 查看验收
 */
const viewAcceptance = () => {
  uni.navigateTo({
    url: "/pages/acceptanceManage/list/list",
  });
};
/**
 * 查看施工日志
 */
const viewconstruction = () => {
  uni.navigateTo({
    url: "/pages/constructionManage/list/list",
  });
};
/**
 * 获取施工日志
 */
const getLogList = async () => {
  try {
    const { data } = await getList({
      size: 3,
      current: 1,
    });
    logList.value = data.records || [];
  } catch (error) {
    console.log(error);
  }
};
/**
 * 获取项目进度
 */

const getProgress = async () => {
  const res = await getProgressList();
  progressList.value = res.data || [];
};
/**
 * 获取日志和进度
 */
const getLogProgressList = () => {
  getLogList();
  getProgress();
};


/**
 * 拨打电话
 */
const showPhonePopup = ref(false)
const handlePhone = ()=>{
  showPhonePopup.value = true
}
</script>
<script>
export default {
  options: {
    styleIsolation: 'shared'
  }
}
</script>
<style lang="scss" scoped>
.user-page {
  padding: 100rpx 25rpx 200rpx 25rpx;
   background: url("http://51-jzt-dev.oss-cn-hangzhou.aliyuncs.com/miniapp/user-bg.png");
  .tenant-popup {
    display: flex;
    font-weight: 400;
    font-size: 36rpx;
    color: #00264a;
    height: 80rpx;
    line-height: 80rpx;
    text-align: left;
    margin-bottom: 35px;

    :deep(.wd-drop-menu) {
      .wd-drop-menu__list {
        display: flex;
        text-align: center;
        background-color: unset;

        .wd-drop-menu__item-title {
          padding: 0 5px;
        }

        .wd-drop-menu__item-title-text {
          margin-right: 30px;
          font-family: PingFang SC, PingFang SC;
          font-weight: 400;
          font-size: 20px;
          color: #00264a;
        }
      }
    }
  }

  .header {
    display: flex;
    margin: 40rpx 0;
    position: relative;

    image {
      width: 128rpx;
      height: 128rpx;
      border-radius: 50%;
    }
    &__phone{
      background: #FFFFFF;
      box-shadow: 0rpx 16rpx 16rpx 0rpx rgba(66,78,102,0.1);
      border-radius: 35rpx 0rpx 0rpx 35rpx;
      border: 2rpx solid #C2D4E8;
      padding:15rpx 12rpx;
      position: absolute;
      right: -30rpx;
      top: 50%;
      transform: translateY(-50%);
      display: flex;
      align-items: center;
      font-size: 24rpx;
      color: #3D3D3D;
      .header__phone__img{
        width: 40rpx;
        height: 40rpx;
        display: inline-block;
        margin-right: 5px;
      }
    }
    &-con {
      padding-left: 20rpx;
      display: flex;
      flex-direction: column;
      justify-content: center;
      /* align-items: center; */

      &-name {
        font-weight: 400;
        font-size: 32rpx;
        color: #121836;
        line-height: 62rpx;
      }

      &-location {
        font-weight: 400;
        font-size: 24rpx;
        color: #86909c;
        line-height: 62rpx;
        display: flex;
        align-items: center;

        .location-icon {
          width: 28rpx;
          height: 28rpx;
          margin-right: 5px;
        }
      }
    }
  }

  .bg-panel {
    width: 560rpx;
    height: 560rpx;
    margin: 18% auto;
    background-repeat: no-repeat;
    background-size: 100%;
    position: relative;

    &-tip {
      color: red;
      font-weight: 400;
      font-size: 28rpx;
      color: #3d3d3d;
      left: 0;
      right: 0;
      margin: auto;
      text-align: center;
      position: absolute;
      bottom: -15px;
    }
  }

  .no-business {
    background-image: url("http://51-jzt-dev.oss-cn-hangzhou.aliyuncs.com/miniapp/user-search.png");
  }

  .no-login {
    background-image: url("http://51-jzt-dev.oss-cn-hangzhou.aliyuncs.com/miniapp/user-noPermission.png");
  }

  .no-phone {
    background-image: url("http://51-jzt-dev.oss-cn-hangzhou.aliyuncs.com/miniapp/user-messages.png");
  }

  .wrapper {
    width: 622rpx;
    background: #ffffff;
    border-radius: 24rpx 24rpx 24rpx 24rpx;
    margin: 80% auto;
    padding-top: 30px;
    box-sizing: border-box;
    text-align: center;
    font-weight: 600;
    font-size: 36rpx;
    color: rgba(0, 0, 0, 0.9);

    .info {
      margin: 20px 0;
      font-weight: 400;
    }

    .btn-group {
      border-top: 1px solid #e7e7e7;
      display: flex;
      justify-content: space-around;
      align-items: center;
      height: 112rpx;

      button {
        width: 50%;
        margin: unset;
        border: unset;
        border-radius: unset;
        font-weight: 500;
        background-color: unset;
        font-weight: 400;
        font-size: 32rpx;
        color: rgba(0, 0, 0, 0.9);
      }

      button::after {
        border: none;
      }

      .confirm {
        color: #007dff;
      }
    }

    .line {
      width: 1rpx;
      height: 100%;
      background: #e7e7e7;
    }
  }
}
</style>
<style>
:deep(.wd-tabbar.is-fixed) {
  bottom: 20px;
}
</style>
